/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.pay.bean;

import com.ibatis.dao.client.DaoManager;
import com.yunhoo.asset.util.PayCodeConstants;
import com.yunhoo.base.bean.FinancialProjectBean;
import com.yunhoo.base.db.dao.DepartmentDao;
import com.yunhoo.base.db.dao.FinancialProjectDao;
import com.yunhoo.base.db.impl.PersonImpl;
import com.yunhoo.base.model.Department;
import com.yunhoo.base.model.FinancialProject;
import com.yunhoo.base.model.PayStyle;
import com.yunhoo.base.model.Person;
import com.yunhoo.pay.db.impl.AbroadGroupImpl;
import com.yunhoo.pay.db.impl.ExpenseImpl;
import com.yunhoo.pay.db.impl.LoanBillImpl;
import com.yunhoo.pay.db.impl.VoucherPubImpl;
import com.yunhoo.pay.model.CostItemAccount;
import com.yunhoo.pay.model.Expense;
import com.yunhoo.pay.model.QueryVouchers;
import com.yunhoo.pay.model.VouCheckInfo;
import com.yunhoo.pay.util.BillOrder;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.Disabled;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.NavigationTool;
import com.yunhoo.sys.util.common.Null;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.pay.util.ToolsMethed;
import com.yunhoo.sys.db.config.DaoConfig;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.richfaces.component.UIDataTable;
import org.richfaces.event.TreeSelectionChangeEvent;

/**
 *
 * @author Administrator
 */
@ManagedBean(name = "expense")
@SessionScoped
public class ExpenseBean {

    private LinkedList<Expense> linkedli = new LinkedList<Expense>();
    private List<Expense> expenselistforcheck = new ArrayList<Expense>();
    private DataModel expenselistModel = new ListDataModel();
    private DataModel expenseCheckViewModel = new ListDataModel();
    private Expense exp = new Expense();
    private CostItemAccount cia = new CostItemAccount();
    private boolean addOrUpdate;
    private boolean showAble = true;
    private boolean editAble = false;
    private UIDataTable personData = null;
    private UIDataTable payData = null;
    private UIDataTable checkData = null;
    private boolean deleteable = false;
    private QueryVouchers qea = new QueryVouchers();
    private List<CostItemAccount> expacc = new ArrayList<CostItemAccount>();
    private boolean submitOrNot = true;
    private boolean saveOrNot = false;
    private boolean updateOrNot = false;
    private int index;
    private Disabled dis = new Disabled();
    private List<SelectItem> payStyleList = null;
    private String payWayType;
    private static String nameSpace = "expensevoucher.";
    private static DaoManager daom;
    private static DepartmentDao dao;
    private static FinancialProjectDao finProjdao;
    private DataModel<FinancialProject> finProjModel = null;
    private String status = "";

    public ExpenseBean() {
        daom = DaoConfig.getDaoManager();
        dao = (DepartmentDao) daom.getDao(DepartmentDao.class);
        finProjdao = (FinancialProjectDao) daom.getDao(FinancialProjectDao.class);
        initStatus();
        initPayStyleList();
        initFinProjList();
        initDate();
    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -10);
        Date begin = calendar.getTime();
        Date end = new Date();
        qea.setNumDateStart(begin);
        qea.setNumDateEnd(end);
    }

    public final void initStatus() {
        saveOrNot = true;
        addOrUpdate = true;
        deleteable = true;
        updateOrNot = true;
        submitOrNot = true;
        showAble = true;
        expacc = new ArrayList();
        expenselistforcheck = IbatisTemplate.queryForList(nameSpace + "queryExpenseForCheck", curOrgCode().trim());
        //expenselistModel.setWrappedData(expenselistforcheck);
        linkedli.clear();
        linkedli.addAll(expenselistforcheck);
        this.setExp(new Expense());
    }

    private void initFinProjList() {
        if (finProjModel == null) {
            finProjModel = new ListDataModel<FinancialProject>();
        }
        try {
            List<FinancialProject> finli = finProjdao.queryAll(new FinancialProject(true));
            finProjModel.setWrappedData(finli);
        } catch (SQLException ex) {
            Logger.getLogger(FinancialProjectBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public final void initPayStyleList() {
        payStyleList = new ArrayList();
        List<PayStyle> Styleli = AbroadGroupImpl.getPaystyleli();
        for (PayStyle d : Styleli) {
            payStyleList.add(new SelectItem(d.getCode(), d.getName()));
        }
    }

    public void payWayChange(ValueChangeEvent event) {
        String code = (String) event.getNewValue();
        List<PayStyle> li = AbroadGroupImpl.getPaystyleli();
        if (!Null.check(li) && !Null.check(code)) {
            for (PayStyle l : li) {
                if (code.trim().equals(l.getCode().trim())) {
                    exp.setPayStyle(l);
                    payWayType = l.getType().trim();
                    //System.out.println("payWayType : " + payWayType);
                }
            }
        }
    }

    public void changeCashPaid() {
        if (!Null.check(exp.getPayStyle().getType())) {
            if (exp.getPayStyle().getType().equals("0")) {
                exp.setCashPaid("1");
            } else {
                exp.setCashPaid("0");
            }
        }
    }

    public void getFirst() {
        if (linkedli.size() == 0) {
            if (expenselistforcheck.isEmpty()) {
                //System.out.println("您尚未录入单据!");
                ToolKit.msgs_info("您尚未录入单据");
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(expenselistforcheck);
                this.setExp(linkedli.getFirst());
                cia.setNumber(exp.getNumber().trim());

                defaults();

                dis.setFirst(true);
                dis.setPreviouse(true);
                dis.setNext(false);
                dis.setLast(false);
            }
            if (exp.getNumberStatus().trim().equals("0")) {
                submitOrNot = true;
            } else {
                submitOrNot = false;
            }
            deleteable = false;
            updateOrNot = false;
        } else {
            this.setExp(linkedli.getFirst());
            cia.setNumber(exp.getNumber().trim());

            defaults();

            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        index = 0;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void getLast() {
        if (linkedli.size() == 0) {
            if (expenselistforcheck.isEmpty()) {
                ToolKit.msgs_info("您尚未录入单据");
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(expenselistforcheck);
                this.setExp(linkedli.getFirst());
                cia.setNumber(exp.getNumber().trim());

                defaults();

                dis.setLast(true);
                dis.setNext(true);
                dis.setPreviouse(false);
                dis.setFirst(false);
            }
            if (exp.getNumberStatus().trim().equals("0")) {
                submitOrNot = true;
            } else {
                submitOrNot = false;
            }
            deleteable = false;
            updateOrNot = false;
        } else {
            this.setExp(linkedli.getLast());
            cia.setNumber(exp.getNumber().trim());

            defaults();

            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        index = linkedli.size() - 1;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void next() {
        if (index < linkedli.size() - 1) {
            index += 1;
            this.setExp(linkedli.get(index));
            cia.setNumber(exp.getNumber().trim());

            defaults();

            dis.setFirst(false);
            dis.setPreviouse(false);
        } else {
            ToolKit.msgs_info("没有了");
            dis.setLast(true);
            dis.setNext(true);
            dis.setFirst(false);
            dis.setPreviouse(false);
            FacesContext.getCurrentInstance().renderResponse();
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void previouse() {
        if (index > 0) {
            index -= 1;
            this.setExp(linkedli.get(index));
            cia.setNumber(exp.getNumber().trim());
            defaults();
            dis.setNext(false);
            dis.setLast(false);
        } else {
            //System.out.println("没有了!");
            ToolKit.msgs_info("没有了");
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
            FacesContext.getCurrentInstance().renderResponse();
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    //生成支付令 
    public void buildpaycode() {
        if (exp.getCostitem().getCode().trim().length() != 0) {
            if (exp.getBudgetSource() != null) {
                if (exp.getCostClass() != null) {
                    if (exp.getCostTypes().getCode().trim().length() != 0) {
                        String pcode = PayCodeConstants.buildPayCodeForLoanBill(exp);
                        exp.setPaycode(pcode);
                    } else {
                        ToolKit.msgs_err("请选择支出渠道");
                        FacesContext.getCurrentInstance().renderResponse();
                    }
                } else {
                    ToolKit.msgs_err("请选择支出类别");
                    FacesContext.getCurrentInstance().renderResponse();
                }
            } else {
                ToolKit.msgs_err("请选择预算来源");
                FacesContext.getCurrentInstance().renderResponse();
            }
        } else {
            ToolKit.msgs_err("请选择经济分类");
            FacesContext.getCurrentInstance().renderResponse();
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    //审核检查
    public void checkandRep() {
//        if (exp.getCostitem().getCode().trim().length() != 0) {
//            if (exp.getBudgetSource() != null) {
//                if (exp.getCostClass() != null) {
//                    if (exp.getCostTypes().getCode().trim().length() != 0) {
//                        if (exp.getPaycode().trim().length() != 0) {
//                            if (exp.getAuditDate() != null && !Null.check(exp.getAuditor())) {
//                                pass();
//                                goback();
//                                NavigationTool.getSelectedUrl("/page/pay/check/table/queryexpenseaccount.xhtml");
//                                //                            } else {
//                                ToolKit.msgs_err("您无权限审核！");
//                                FacesContext.getCurrentInstance().renderResponse();
//                                //                            }
//                        } else {
//                            ToolKit.msgs_err("请点击支付令");
//                            FacesContext.getCurrentInstance().renderResponse();
//                            //                        }
//                    } else {
//                        ToolKit.msgs_err("请选择支出渠道");
//                        FacesContext.getCurrentInstance().renderResponse();
//                        //                    }
//                } else {
//                    ToolKit.msgs_err("请选择支出类别");
//                    FacesContext.getCurrentInstance().renderResponse();
//                    //                }
//            } else {
//                ToolKit.msgs_err("请选择预算来源");
//                FacesContext.getCurrentInstance().renderResponse();
//                //            }
//
//        } else {
//            ToolKit.msgs_err("请选择经济分类");
//            FacesContext.getCurrentInstance().renderResponse();
//            //        }

        if (exp.getCostitem().getCode() == null) exp.getCostitem().setCode("");
        if (exp.getBudgetSource() == null) exp.setBudgetSource("");
        if (exp.getCostClass() == null) exp.setCostClass("");
        if (exp.getCostTypes().getCode() == null) exp.getCostTypes().setCode("");
        if (exp.getPaycode() == null) exp.setPaycode("");

        if (exp.getAuditDate() == null || Null.check(exp.getAuditor())) {
            ToolKit.msgs_err("您无权限审核！");
        } else {
            pass();
            goback();
        }
    }

    public void pass() {
        exp.setNumberStatus("2");
        exp.setAuditor(curPerNum().trim());
        exp.setRemain(exp.getCheckaccount() - exp.getRepayment());
        LoanBillImpl.updateLoanBillForAudit(exp);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(exp.getNumber());
        info.setVouType(exp.getVoutype());
        info.setCheckInfo(exp.getCheckInfo());
        VoucherPubImpl.insertCheckInfo(info);

//        Person receiver = PersonImpl.queryByPerNumber(exp.getUser().getCpsn_number().trim());
//        Person sender = PersonImpl.queryByPerNumber(curPerNum().trim());
//        ToolsMethed.sendMail(sender, receiver, "审核通过", "审核OK");
    }

    private void initCheckValue(Expense exp) {
        this.exp = exp;
        cia.setNumber(exp.getNumber().trim());
        defaults();
        
        if (exp.getCostitem().getCode() == null) exp.getCostitem().setCode("");
        if (exp.getBudgetSource() == null) exp.setBudgetSource("");
        if (exp.getCostClass() == null) exp.setCostClass("");
        if (exp.getCostTypes().getCode() == null) exp.getCostTypes().setCode("");
        if (exp.getPaycode() == null) exp.setPaycode("");
    }

    public void passWithParam(Expense exp) {
        initCheckValue(exp);
        exp.setNumberStatus("2");
        exp.setAuditor(curPerNum().trim());
        exp.setRemain(exp.getCheckaccount() - exp.getRepayment());
        LoanBillImpl.updateLoanBillForAudit(exp);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(exp.getNumber());
        info.setVouType(exp.getVoutype());
        info.setCheckInfo(exp.getCheckInfo());
        VoucherPubImpl.insertCheckInfo(info);

//        Person receiver = PersonImpl.queryByPerNumber(exp.getUser().getCpsn_number().trim());
//        Person sender = PersonImpl.queryByPerNumber(curPerNum().trim());
//        ToolsMethed.sendMail(sender, receiver, "审核通过", "审核OK");
    }

    //支付检查
    public void checkPayandRep() {
        String payStatus = exp.getNumberStatus();
        exp.setNumberStatus("2");
        if (Null.check(exp.getPayStyle().getCode())) {
            ToolKit.msgs_err("请选择支付方式");
        } else if (exp.getPayaccount() == null) {
            ToolKit.msgs_err("请输入支付金额");
        } //        else if (exp.getRepayment() == null) {
        //            DocumentQueryConditionBean dqcb = (DocumentQueryConditionBean) FacesUtils.getManagedBean("queryBean");
        //            dqcb.setErr(new ErrMessage("请输入还款金额"));
        //        } 
        else if (exp.getPayDate() == null) {
            ToolKit.msgs_err("请选择支付日期");
        } else if ("1".equals(payWayType) && Null.check(exp.getReceive())) {
            ToolKit.msgs_err("请填写收款人!");
        } else if (exp.getPayaccount() + exp.getRepayment() != exp.getCheckaccount()) {
            ToolKit.msgs_err("支付金额 + 冲账金额 = 核定金额,才可");
        } else if (exp.getCashPaid() == null) {
            ToolKit.msgs_err("是否现金付讫！");
        } else if (Null.check(payStatus)) {
            ToolKit.msgs_err("是否支付完毕！");
        } else if ("1".equals(exp.getCashPaid()) && exp.getTicketcode().length() != 0) {
            ToolKit.msgs_err("现金付讫不需填写支付凭证号");
        } else if ("0".equals(exp.getCashPaid()) && Null.check(exp.getTicketcode())) {
            ToolKit.msgs_err("请填写支付凭证号");
        } else {
            if ("0".equals(exp.getCashPaid())) {
                String str = exp.getNumber() + exp.getTicketcode();
                exp.setTicketcode(str);
            }

            exp.setNumberStatus(payStatus);
            pay();  //支付
            NavigationTool.getSelectedUrl("/page/pay/payment/table/queryexpenseaccount.xhtml");
        }
    }

    public void pay() {
        //exp.setNumberStatus("4");
        exp.setPayer(curPerNum().trim());
        LoanBillImpl.updateLoanBillForPay(exp);

//        Person receiver = PersonImpl.queryByPerNumber(exp.getUser().getCpsn_number().trim());
//        Person sender = PersonImpl.queryByPerNumber(curPerNum().trim());

        queryExpenseAccount();
//        expenselistforcheck = IbatisTemplate.queryForList(nameSpace + "queryExpenseForCheck", curOrgCode().trim());
//        expenselistModel.setWrappedData(expenselistforcheck);
        //ToolsMethed.sendMail(sender, receiver, "支付成功", "支付成功");
    }

    public void cancel() {
        initStatus();
        expenselistModel.setWrappedData(expenselistforcheck);
        qea = new QueryVouchers();
        status = "";
    }

    public void back() {
//        Person receiver = PersonImpl.queryByPerNumber(exp.getUser().getCpsn_number().trim());
//        Person sender = PersonImpl.queryByPerNumber(curPerNum().trim());
//        ToolsMethed.sendMail(sender, receiver, "审核未通过", "请重新修改");

        Map map = new HashMap();
        map.put("number", exp.getNumber().trim());
        map.put("orgCode", curOrgCode().trim());
        IbatisTemplate.update("loanbill.voucherBack", map);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(exp.getNumber());
        info.setVouType(exp.getVoutype());
        info.setCheckInfo(exp.getCheckInfo());
        VoucherPubImpl.insertCheckInfo(info);

        goback();
    }

    public void goback() {
        expenselistforcheck = IbatisTemplate.queryForList(nameSpace + "queryExpenseForCheck", curOrgCode().trim());
        expenselistModel.setWrappedData(expenselistforcheck);
        NavigationTool.getSelectedUrl("/page/pay/check/table/queryexpenseaccount.xhtml");

    }

    public void showcheckdetail() {
        this.setExp((Expense) this.expenselistModel.getRowData());
        //System.out.println("" + this.getExp().getCostTypes().getCode());
        cia.setNumber(exp.getNumber().trim());
        expacc = ExpenseImpl.expensaccount(exp.getNumber().trim());
        index = this.expenselistModel.getRowIndex();
        linkedli.clear();
        linkedli.addAll(expenselistforcheck);
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        defaults();
        NavigationTool.getSelectedUrl("/page/pay/check/operation/expenseaccount.xhtml");
    }

    public void goBackPayList() {
        queryExpenseAccount();
//        expenselistforcheck = IbatisTemplate.queryForList(nameSpace + "queryExpenseForCheck", curOrgCode().trim());
//        if (expenselistforcheck != null && expenselistforcheck.size() > 0) {
//            expenselistModel.setWrappedData(expenselistforcheck);
//        }
        //System.out.println("list00000++ :" + expenselistforcheck.size());
        NavigationTool.getSelectedUrl("/page/pay/payment/table/queryexpenseaccount.xhtml");
    }

    public void showPayDetail() {
        this.setExp((Expense) this.expenselistModel.getRowData());
        cia.setNumber(exp.getNumber().trim());
        expacc = ExpenseImpl.expensaccount(exp.getNumber().trim());
        //System.out.println("expacc list size:" + expacc.size());
        index = this.expenselistModel.getRowIndex();
        linkedli.clear();
        linkedli.addAll(expenselistforcheck);
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        defaults();
        NavigationTool.getSelectedUrl("/page/pay/payment/operation/expenseaccount.xhtml");
    }

    public void rescind() {
        IbatisTemplate.update("loanbill.voucherRescind", exp);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(exp.getNumber());
        info.setVouType(exp.getVoutype());
        VoucherPubImpl.deleteCheckInfo(info);

        initStatus();
        expenselistModel.setWrappedData(expenselistforcheck);
        goback();
    }

    public void payrescind() {
        //System.out.println("进入撤回方法");
        IbatisTemplate.update("loanbill.payVoucherRescind", exp);
        //System.out.println("修改撤单状态");
        initStatus();
        expenselistModel.setWrappedData(expenselistforcheck);
        //System.out.println("初始化");
        NavigationTool.getSelectedUrl("/page/pay/payment/table/queryexpenseaccount.xhtml");
    }
    //选择预算项目

    public void selectProjForQuery() {
        FinancialProject fProj = finProjModel.getRowData();
        qea.getProject().setFinCode(fProj.getFinCode());
        qea.getProject().setFinName(fProj.getFinName());
    }
    //选择部门

    public void selecteDeptForQuery(TreeSelectionChangeEvent event) {
        Department dp = (Department) TreeUtil.listener(event);
        qea.getDept().setCode(dp.getCode());
        qea.getDept().setName(dp.getName());
    }
    //动态查询 表单列表

    public void queryExpenseAccount() {
        Map map = new HashMap();
        map.put("orgCode", curOrgCode().trim());
        map.put("number", qea.getNumber().trim());
        map.put("affair", qea.getAffair().trim());
        map.put("projcode", Null.convert(qea.getProject().getFinCode()).trim());
        map.put("deptname", Null.convert(qea.getDept().getName()).trim());
        map.put("cpsn_name", Null.convert(qea.getUser().getCpsn_number()).trim());
        map.put("budgetSource", qea.getBudgetSource().trim());
        map.put("costcode", Null.convert(qea.getCostitem().getCode()).trim());
        map.put("paycode", qea.getPaycode().trim());
        map.put("costClass", qea.getCostClass().trim());
        map.put("costType", qea.getCostTypes().getCode().trim());
        map.put("payStyle", qea.getPayStyle().trim());
        map.put("ticketcode", qea.getTicketcode().trim());
        map.put("numDateStart", qea.getNumDateStart());
        map.put("numDateEnd", qea.getNumDateEnd());
        map.put("auditDateStart", qea.getAuditDateStart());
        map.put("auditDateEnd", qea.getAuditDateEnd());
        map.put("payDateStart", qea.getPayDateStart());
        map.put("payDateEnd", qea.getPayDateEnd());
        map.put("totalStart", qea.getTotalStart());
        map.put("totalEnd", qea.getTotalEnd());
        map.put("checkaccountStart", qea.getCheckaccountStart());
        map.put("checkaccountEnd", qea.getCheckaccountEnd());
        map.put("payaccountStart", qea.getPayaccountStart());
        map.put("payaccountEnd", qea.getPayaccountEnd());
        map.put("sql", Null.convert(status).trim());
        map.put("billOrder", BillOrder.checkOrder);//单据排列顺序
        map.put("billRange", "'2','4','6'");
        expenselistforcheck = IbatisTemplate.queryForList(nameSpace + "expenseaccountquery", map);
        expenselistModel.setWrappedData(expenselistforcheck);
    }

    public void initCheckViewList() {
        Map map = new HashMap();
        map.put("voustatus", "0");
        map.put("orgCode", curOrgCode().trim());
        expenselistforcheck = IbatisTemplate.queryForList(nameSpace + "queryExpenseViewList", map);
        expenseCheckViewModel.setWrappedData(expenselistforcheck);

    }

    public void showFromCheckView(Expense expense, DataModel viewModel) {
        this.setExp(expense);
        cia.setNumber(exp.getNumber().trim());
        expacc = ExpenseImpl.expensaccount(exp.getNumber().trim());
        index = viewModel.getRowIndex();
        expenselistforcheck = (List<Expense>) viewModel.getWrappedData();
        linkedli.clear();
        linkedli.addAll(expenselistforcheck);
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        defaults();
        NavigationTool.getSelectedUrl("/page/pay/check/operation/expenseaccount.xhtml");
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void showFromPayView(Expense expense, DataModel viewModel) {
        this.setExp(expense);
        cia.setNumber(exp.getNumber().trim());
        expacc = ExpenseImpl.expensaccount(exp.getNumber().trim());
        index = viewModel.getRowIndex();
        expenselistforcheck = (List<Expense>) viewModel.getWrappedData();
        linkedli.clear();
        linkedli.addAll(expenselistforcheck);
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        defaults();
        NavigationTool.getSelectedUrl("/page/pay/payment/operation/expenseaccount.xhtml");
    }

    public void exportExcelForCheck() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("审核单据报销单列表");
        String[] excelColumns = initTabeleHeader();
        List<Expense> rows = expenselistforcheck;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("审核单据报销单列表");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (Expense row : rows) {
            createTableRow(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        ExpenseBean.exportExcel(demoWorkBook, demoSheet);

    }

    //初始化表头信息
    public String[] initTabeleHeader() {
        String[] excelColumns = {"单据编号", "单据状态", "单据日期", "报销内容", "报销金额", "预算项目", "经手人员", "部门", "支出类别",
            "预算来源", "经济分类", "支出渠道", "支付令", "核定金额", "还款金额", "待支付金额", "审核日期", "审核人", "支付金额", "支付日期", "出纳"};
        return excelColumns;
    }

    public static void createTableRow(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, Expense ep, int rowIndex) {
        //创建第rowIndex行
        CreationHelper createHelper = demoWorkBook.getCreationHelper();
        HSSFCellStyle dstyle = demoWorkBook.createCellStyle();
        dstyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));//格式
        HSSFCellStyle dstyled = demoWorkBook.createCellStyle();
        dstyled.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));


        HSSFCell cell = null;
        HSSFRow row = demoSheet.createRow(rowIndex);
        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(ep.getNumber()));
        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.functionNumberStatus().get(ep.getNumberStatus())));
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertDate(ep.getNumDate()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(3);
        cell.setCellValue(PayCodeConstants.convertString(ep.getAffair()));
        cell = row.createCell(4);
        cell.setCellValue(PayCodeConstants.convertDouble(ep.getTotal()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(5);
        cell.setCellValue(PayCodeConstants.convertString(ep.getProject().getFinName()));
        cell = row.createCell(6);
        cell.setCellValue(PayCodeConstants.convertString(ep.getUser().getCpsn_name()));
        cell = row.createCell(7);
        cell.setCellValue(PayCodeConstants.convertString(ep.getDept().getName()));
        cell = row.createCell(8);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.formateCostClass().get(ep.getCostClass())));
        cell = row.createCell(9);
        cell.setCellValue(PayCodeConstants.convertString(ep.getBudgetSource()));
        cell = row.createCell(10);
        cell.setCellValue(PayCodeConstants.convertString(ep.getCostitem().getName()));
        cell = row.createCell(11);
        cell.setCellValue(PayCodeConstants.convertString(ep.getCostTypes().getName()));
        cell = row.createCell(12);
        cell.setCellValue(PayCodeConstants.convertString(ep.getPaycode()));
        cell = row.createCell(13);
        cell.setCellValue(PayCodeConstants.convertDouble(ep.getCheckaccount()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(14);
        cell.setCellValue(PayCodeConstants.convertDouble(ep.getRepayment()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(15);
        cell.setCellValue(PayCodeConstants.convertDouble(ep.getRemain()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(16);
        if (ep.getAuditDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(ep.getAuditDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(17);
        cell.setCellValue(PayCodeConstants.convertString(ep.getAuditor()));
        cell = row.createCell(18);
        cell.setCellValue(PayCodeConstants.convertDouble(ep.getPayaccount()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(19);
        if (ep.getPayDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(ep.getPayDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(20);
        cell.setCellValue(PayCodeConstants.convertString(ep.getPayer()));

    }

    public static void exportExcel(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet) {
        try {
            String strfileName = "book.xls";
            FileOutputStream fos = null;
            //导出
            demoSheet.setGridsPrinted(true);//demoSheet
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/upload") + "/" + strfileName;//strfileName
            File exportFile = new File(excelName);
            fos = new FileOutputStream(exportFile);//fos
            demoWorkBook.write(fos);//demoWorkBook
            fos.close();

            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + strfileName);//strfileName
            httpServletResponse.setContentLength((int) exportFile.length());//exportFile
            httpServletResponse.setContentType("application/x-download");
            //httpServletResponse.setContentType("application/vnd.ms-excel");
            byte[] b = new byte[1024];
            int i = 0;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
            servletOutputStream.flush();
            ctx.responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void exportExcelForPay() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("支付单据借款单列表");
        String[] excelColumns = initTabeleHeaderForPay();
        List<Expense> rows = expenselistforcheck;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("支付单据借款单列表");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (Expense row : rows) {
            createTableRowForPay(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        ExpenseBean.exportExcelForPay(demoWorkBook, demoSheet);

    }

    //初始化表头信息
    public String[] initTabeleHeaderForPay() {
        String[] excelColumns = {"单据编号", "单据状态", "单据日期", "报销内容", "报销金额", "预算项目", "经手人员", "部门", "支出类别",
            "预算来源", "经济分类", "支出渠道", "支付令", "核定金额", "审核日期", "审核人", "支付方式", "支票号", "支付金额", "支付日期", "出纳"};
        return excelColumns;
    }

    public static void createTableRowForPay(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, Expense epp, int rowIndex) {
        //创建第rowIndex行
        CreationHelper createHelper = demoWorkBook.getCreationHelper();
        HSSFCellStyle dstyle = demoWorkBook.createCellStyle();
        dstyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));//格式
        HSSFCellStyle dstyled = demoWorkBook.createCellStyle();
        dstyled.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));

        HSSFCell cell = null;
        HSSFRow row = demoSheet.createRow(rowIndex);
        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(epp.getNumber()));
        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.functionNumberStatus().get(epp.getNumberStatus())));
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertDate(epp.getNumDate()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(3);
        cell.setCellValue(PayCodeConstants.convertString(epp.getAffair()));
        cell = row.createCell(4);
        cell.setCellValue(PayCodeConstants.convertDouble(epp.getTotal()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(5);
        cell.setCellValue(PayCodeConstants.convertString(epp.getProject().getFinName()));
        cell = row.createCell(6);
        cell.setCellValue(PayCodeConstants.convertString(epp.getUser().getCpsn_name()));
        cell = row.createCell(7);
        cell.setCellValue(PayCodeConstants.convertString(epp.getDept().getName()));
        cell = row.createCell(8);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.formateCostClass().get(epp.getCostClass())));
        cell = row.createCell(9);
        cell.setCellValue(PayCodeConstants.convertString(epp.getBudgetSource()));
        cell = row.createCell(10);
        cell.setCellValue(PayCodeConstants.convertString(epp.getCostitem().getName()));
        cell = row.createCell(11);
        cell.setCellValue(PayCodeConstants.convertString(epp.getCostTypes().getName()));
        cell = row.createCell(12);
        cell.setCellValue(PayCodeConstants.convertString(epp.getPaycode()));
        cell = row.createCell(13);
        cell.setCellValue(PayCodeConstants.convertDouble(epp.getCheckaccount()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(14);
        if (epp.getAuditDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(epp.getAuditDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(15);
        cell.setCellValue(PayCodeConstants.convertString(epp.getAuditor()));
        cell = row.createCell(16);
        cell.setCellValue(PayCodeConstants.convertString(epp.getPayStyle().getCode()));
        cell = row.createCell(17);
        cell.setCellValue(PayCodeConstants.convertString(epp.getTicketcode()));
        cell = row.createCell(18);
        cell.setCellValue(PayCodeConstants.convertDouble(epp.getPayaccount()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(19);
        if (epp.getPayDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(epp.getPayDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(20);
        cell.setCellValue(PayCodeConstants.convertString(epp.getPayer()));

    }

    public static void exportExcelForPay(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet) {
        try {
            String strfileName = "book.xls";
            FileOutputStream fos = null;
            //导出
            demoSheet.setGridsPrinted(true);//demoSheet
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/upload") + "/" + strfileName;//strfileName
            File exportFile = new File(excelName);
            fos = new FileOutputStream(exportFile);//fos
            demoWorkBook.write(fos);//demoWorkBook
            fos.close();

            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + strfileName);//strfileName
            httpServletResponse.setContentLength((int) exportFile.length());//exportFile
            httpServletResponse.setContentType("application/x-download");
            //httpServletResponse.setContentType("application/vnd.ms-excel");
            byte[] b = new byte[1024];
            int i = 0;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
            servletOutputStream.flush();
            ctx.responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void defaults() {
        if ("0".equals(exp.getNumberStatus().trim()) && "C".equalsIgnoreCase(curPerRole().trim())) {
            exp.setCheckaccount(exp.getTotal());
            exp.setAuditor(curPerName().trim());
            exp.setAuditDate(new Date());
        }
        if ("2".equals(exp.getNumberStatus().trim()) && "P".equalsIgnoreCase(curPerRole().trim())) {
            exp.setPayer(curPerName().trim());
            exp.setReceive(exp.getFeePer().getCpsn_name());
            exp.setPayaccount(exp.getCheckaccount());
            exp.setPayDate(new Date());
            forCashPaid();
        }
        expacc = ExpenseImpl.expensaccount(cia.getNumber().trim());
    }

    public void forCashPaid() {
        if (!Null.check(exp.getPayStyle().getType()) && Null.check(exp.getCashPaid())) {
            if (exp.getPayStyle().getType().equals("0")) {
                exp.setCashPaid("1");
            } else {
                exp.setCashPaid("0");
            }
        }
    }
    //getter and setter 

    public Expense getExp() {
        return exp;
    }

    public void setExp(Expense exp) {
        this.exp = exp;
    }

    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }

    public boolean isEditAble() {
        return editAble;
    }

    public void setEditAble(boolean editAble) {
        this.editAble = editAble;
    }

    public boolean isShowAble() {
        return showAble;
    }

    public void setShowAble(boolean showAble) {
        this.showAble = showAble;
    }

    public boolean isDeleteable() {
        return deleteable;
    }

    public void setDeleteable(boolean deleteable) {
        this.deleteable = deleteable;
    }

    public List<CostItemAccount> getExpacc() {
        return expacc;
    }

    public void setExpacc(List<CostItemAccount> expacc) {
        this.expacc = expacc;
    }

    public CostItemAccount getCia() {
        return cia;
    }

    public void setCia(CostItemAccount cia) {
        this.cia = cia;
    }

    public boolean isSubmitOrNot() {
        return submitOrNot;
    }

    public void setSubmitOrNot(boolean submitOrNot) {
        this.submitOrNot = submitOrNot;
    }

    public QueryVouchers getQea() {
        return qea;
    }

    public void setQea(QueryVouchers qea) {
        this.qea = qea;
    }

    public boolean isSaveOrNot() {
        return saveOrNot;
    }

    public void setSaveOrNot(boolean saveOrNot) {
        this.saveOrNot = saveOrNot;
    }

    public boolean isUpdateOrNot() {
        return updateOrNot;
    }

    public void setUpdateOrNot(boolean updateOrNot) {
        this.updateOrNot = updateOrNot;
    }

    public Disabled getDis() {
        return dis;
    }

    public void setDis(Disabled dis) {
        this.dis = dis;
    }

    public UIDataTable getCheckData() {
        return checkData;
    }

    public void setCheckData(UIDataTable checkData) {
        this.checkData = checkData;
    }

    public DataModel<Expense> getExpenselistModel() {
        return expenselistModel;
    }

    public void setExpenselistModel(DataModel expenselistModel) {
        this.expenselistModel = expenselistModel;
    }

    public List<Expense> getExpenselistforcheck() {
        return expenselistforcheck;
    }

    public void setExpenselistforcheck(List<Expense> expenselistforcheck) {
        this.expenselistforcheck = expenselistforcheck;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public LinkedList<Expense> getLinkedli() {
        return linkedli;
    }

    public void setLinkedli(LinkedList<Expense> linkedli) {
        this.linkedli = linkedli;
    }

    public UIDataTable getPayData() {
        return payData;
    }

    public void setPayData(UIDataTable payData) {
        this.payData = payData;
    }

    public List<SelectItem> getPayStyleList() {
        return payStyleList;
    }

    public void setPayStyleList(List<SelectItem> payStyleList) {
        this.payStyleList = payStyleList;
    }

    public String getPayWayType() {
        return payWayType;
    }

    public void setPayWayType(String payWayType) {
        this.payWayType = payWayType;
    }

    public UIDataTable getPersonData() {
        return personData;
    }

    public void setPersonData(UIDataTable personData) {
        this.personData = personData;
    }
    //

    private String curPerNum() {
        return LoginParam.getPer().getCpsn_number();
    }

    private String curPerName() {
        return LoginParam.getPer().getCpsn_name();
    }

    private String curDeptCode() {
        return LoginParam.getDept().getCode();
    }

    private String curDeptName() {
        return LoginParam.getDept().getName();
    }

    private Date curLoginDate() {
        return LoginParam.getLoginDate();
    }

    private Integer curIyear() {
        return LoginParam.getIyear();
    }

    private String curOrgCode() {
        return LoginParam.getOrg().getCode();
    }

    private String curPerRole() {
        return LoginParam.getPer().getRole();
    }

    public DataModel getExpenseCheckViewModel() {
        return expenseCheckViewModel;
    }

    public void setExpenseCheckViewModel(DataModel expenseCheckViewModel) {
        this.expenseCheckViewModel = expenseCheckViewModel;
    }

    public static String getNameSpace() {
        return nameSpace;
    }

    public static void setNameSpace(String nameSpace) {
        ExpenseBean.nameSpace = nameSpace;
    }

    public DataModel<FinancialProject> getFinProjModel() {
        return finProjModel;
    }

    public void setFinProjModel(DataModel<FinancialProject> finProjModel) {
        this.finProjModel = finProjModel;
    }

    public List<SelectItem> getSelectItemList() {
        List<SelectItem> selectItemList = new ArrayList<SelectItem>();
        selectItemList.add(new SelectItem("0,3", "未审核"));
        selectItemList.add(new SelectItem("2,4,6", "已审核"));
        return selectItemList;
    }

    public List<SelectItem> getPayStatusList() {
        List<SelectItem> payStatusList = new ArrayList<SelectItem>();
        payStatusList.add(new SelectItem("0,2,3", "未支付"));
        payStatusList.add(new SelectItem("4,6", "已支付"));
        return payStatusList;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}
